/*
	flad : Copyright 2010 Dale J Williams

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package lads.flad {
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import lads.flad.flad;
	import lads.flad.GameCore;
	import lads.flad.interfaces.IBounds;
	import lads.flad.interfaces.IScene;
	import lads.flad.screens.GameScreen;
	
	/**
	 * GameEngine: Runs the scene and subsequent objects.
	 * @author Dale J Williams
	 * @version 2.0
	 */
	public class GameEngine extends GameScreen {
				
		protected var _scene	:IScene;
		protected var _screen	:Rectangle;
		
		public function GameEngine(core:GameCore) {
			this.core = core;
			super("engine");
			init();
		}
		
		private function init():void {
			_screen = new Rectangle();
		}

		public function setScene(scene:IScene):void {
			if (_scene && contains(DisplayObject(_scene))) {
				_scene.stopAll();
				removeChild(DisplayObject(_scene));
			}
			_scene = scene;
			_scene.engine = this;
			addChild(_scene.host);
			_scene.startAll();
		}
		
		override public function animIn():void {
			super.animIn();
			start();			
		}
		
		/// start the engine, loops
		public function start():void {
			addEventListener(Event.ENTER_FRAME, update);	
		}
		
		/// stop the engine, loops
		public function stop():void {
			removeEventListener(Event.ENTER_FRAME, update);
		}
		
		override public function animOut():void {
			stop();
			animOutComplete();
		}
		
		/// 
		protected function update(e:Event = null):void {
			_scene.updateAll();
		}
		
		private function withinScreen(boundObject:IBounds):Boolean {
			return boundObject.bounds.right > _screen.left && boundObject.bounds.left < _screen.right && boundObject.bounds.bottom > _screen.top && boundObject.bounds.top < _screen.bottom;
		} 
		
	}

}